'use strict';

const app = require('express')();
const createError = require('http-errors');

const log = require('./commons/factories/logFactory');
const config = require('./commons/factories/configuration');

const serverCfg = config.get('server');
const appLog = log.getLogger('app');
const zizEnv = serverCfg.NODE_ENV;

// require('./models').Route.create({
//     serviceName: 'ziztour-generic-service',
//     uri: '/generic/addr/area',
//     host: '192.168.1.240',
//     port: 33000,
//     method: '',
//     description: '城市-区域',
//     anonymous: 1,
//     internal: 0,
//     status: 1
// }, function(err, arr) {
//     console.error(err, arr);
// });

app.set('views', serverCfg.VIEWS_DIR);
app.set('view engine', 'jade');

//路由过滤
app.use('/api', require('./middleware/route_filter')());

//Oauth2
app.use('/api', require('./middleware/oauth')());

//路由重定向
app.use('/api', require('./middleware/http_forward')());

app.use((req, res, next) => {
    const err = createError(404, 'Not Found');
    appLog.error("找不到页面：" + req.url, err);
    next(err);
});
app.use((err, req, res, next) => {
    res.status(err.status || 500);
    appLog.error("出错了：" + req.url, err);
    //req.headers['x-requested-with'] === 'XMLHttpRequest'
    if (req.xhr) {
        res.json({
            message: err.message,
            error: zizEnv === 'development' ? err : {}
        });
    } else {
        res.render('error', {
            message: err.message,
            error: zizEnv === 'development' ? err : {}
        });
    }
});

module.exports = app;